// by Xeno
// Commented/edited by Tyrghen

private ["_box_ownside", "_box_otherside","_other_side","_box_array"];

_box_array = [];
_box_array = d_player_ammobox_pos;

_box_ownside = d_the_base_box createVehicleLocal (_box_array select 0);
_box_ownside setDir (_box_array select 1);
_box_ownside setPos (_box_array select 0);
_box_ownside setVariable ["ARTY_N_LOG_IGNORE_OBJECT",true];
player reveal _box_ownside;
_box_ownside allowdamage False;
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"playerammobox.sqf","Own Ammo Box created at", getPos _box_ownside]; };
_box_otherside = objNull;
If (d_create_both_boxes) then {
	_box_array = d_second_ammobox_pos;
	_box_otherside = d_the_base_box createVehicleLocal (_box_array select 0);
	_box_otherside setDir (_box_array select 1);
	_box_otherside setPos (_box_array select 0);
	_box_otherside setVariable ["ARTY_N_LOG_IGNORE_OBJECT",true];
	player reveal _box_otherside;
	_box_otherside allowdamage False;
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"playerammobox.sqf","Other Ammo Box created at", getPos _box_otherside]; };
};
_other_side = "EAST";
If (d_own_side == "WEST") then {_other_side = "EAST";} else {_other_side = "WEST";};

// This will wait for the server script to create the weapon arrays. From there it will start to fill the boxes.
while {count((["d_weapon_array_enemy",[]] call XNetGetJIP)) <= 0} do {
	_items = ;
	sleep 0.5;
};

while {True} do{
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"playerammobox.sqf","Filling the base box", getPos _box_ownside]; };
	if (!isnull _box_ownside) then {
		[_box_ownside,d_own_side] spawn x_weaponcargo;
	};
	if (!isnull _box_otherside) then {
		[_box_otherside,_other_side] spawn x_weaponcargo;
	};
	// We wait that the player gets close to the box before starting the refill wait. This avoids unnecessary refill when the player is in the field.
	waituntil { sleep 1; ((player distance _box_ownside) < 100) };
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"playerammobox.sqf","Waiting for player to go away", getPos _box_ownside]; };
	// We wait that the player is far enough from the box before filling it.
	waituntil { sleep 5; ((player distance _box_ownside) > 100) };
	sleep 1200;
};
